<template>
  <div>
    <div class="topFiltrate">
      <p :class="dateType == 1 ? 'activep' : ''" @click="changedate(1)">七天</p>
      <p :class="dateType == 2 ? 'activep' : ''" @click="changedate(2)">本月</p>
      <p :class="dateType == 3 ? 'activep' : ''" @click="changedate(3)">半年</p>
      <p :class="dateType == 4 ? 'activep' : ''" @click="changedate(4)">
        自定义
        <a-range-picker
          v-model="rangeDate"
          :format="dateFormatList"
          :disabled-date="disabledDate"
          @change="ondateChange"
        />
      </p>
    </div>
    <div class="app-container">
      <a-row type="flex" :gutter="10">
        <a-col :span="12" style="margin-top: 16px">
          <a-card title="产量">
            <bar-chart :chart-data="chartDataBar"></bar-chart>
          </a-card>
        </a-col>
        <a-col :span="12" style="margin-top: 16px">
          <a-card
            :tab-list="tabListNoTitlesort"
            :active-tab-key="noTitleKeysort"
            @tabChange="(key) => onTabChangeSort(key, 'noTitleKeysort')"
          >
            <bar-chart-sort
              :chart-data="chartDataBarsort"
              :str="sortstr"
            ></bar-chart-sort>
          </a-card>
        </a-col>
        <a-col :span="16" style="margin-top: 16px">
          <a-card
            :tab-list="tabListNoTitle"
            :active-tab-key="noTitleKey"
            @tabChange="(key) => onTabChange(key, 'noTitleKey')"
          >
            <linechart :chart-data="chartData" :str="str"></linechart>
          </a-card>
        </a-col>
        <a-col :span="8" style="margin-top: 16px">
          <a-card
            :tab-list="ListNoTitlepro"
            :active-tab-key="noTitleKeypro"
            @tabChange="(key) => onTabChangepro(key, 'noTitleKeypro')"
          >
            <div
              class="progressbox"
              style="min-height: 350px"
              v-if="noTitleKeypro == 2"
            >
              <div v-if="TimeActivationData.length > 0">
                <p v-for="(item, index) in TimeActivationData" :key="index">
                  <span class="progressname">{{ item.groupName }}</span>
                  <span style="display: inline-block; width: 70%"
                    ><a-progress
                      strokeColor="#FDBA00"
                      :percent="Math.round(item.groupTimeActivation * 100)"
                      :format="percent => `${percent}%`"
                  /></span>
                </p>
              </div>

              <a-empty style="margin-top: 60px" v-else />
            </div>
            <div
              class="progressbox"
              style="min-height: 350px"
              v-if="noTitleKeypro == 3"
            >
              <div v-if="QualityActivationData.length > 0">
                <p v-for="(item, index) in QualityActivationData" :key="index">
                  <span class="progressname">{{ item.groupName }}</span>
                  <span style="display: inline-block; width: 70%"
                    ><a-progress
                      strokeColor="#FDBA00"
                      :percent="Math.round(item.groupQualityActivation * 100)"
                      :format="percent => `${percent}%`"
                  /></span>
                </p>
              </div>
              <a-empty style="margin-top: 60px" v-else />
            </div>
            <div
              class="progressbox"
              style="min-height: 350px"
              v-if="noTitleKeypro == 1"
            >
              <a-empty style="margin-top: 60px" />
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import linechart from "./component/linechart";
import BarChart from "./component/BarChart";
import BarChartSort from "./component/BarChartSort";
import {
  timeCalculation,
  formatCurrentMonth,
  getDayAll,
  getYearAndMonth,
} from "../../unit/tool";
import api from "@/api/equipment";
import moment from 'moment';

export default {
  name: "index",
  components: {
    linechart,
    BarChart,
    BarChartSort,
  },
  data() {
    return {
      dateType: 1,
      chartData: {
        expectedData: [],
        date: [],
        name: [],
      },
      chartDataBar: {
        expectedData: [],
        date: [],
      },
      chartDataBarsort: {
        expectedData: [],
        date: [],
      },
      tabListNoTitle: [
        { key: "1", tab: "开机率" },
        { key: "2", tab: "运行时间" },
        // { key: "3", tab: "故障时间" },
      ],
      noTitleKey: "1",
      tabListNoTitlesort: [
        { key: "1", tab: "运行时间排名(小时)" },
        { key: "2", tab: "产量排名(个)" },
      ],
      noTitleKeysort: "1",
      ListNoTitlepro: [
        { key: "2", tab: "时间稼动率" },
        // { key: "3", tab: "性能稼动率" },
        // { key: "1", tab: "设备综合效率" },
      ],
      noTitleKeypro: "2",
      startTime: null,
      endTime: null,
      timeParames: {
        startTime: null,
        endTime: null,
        UserName: null,
        compid: null,
      },
      rangeDate: null,
      dateFormatList: ["YYYY-MM-DD", "YYYY-MM-DD"],
      TimeActivationData: [],
      QualityActivationData: [],
      str: "%",
      sortstr: "小时",
      
    };
  },
  created() {
    let roleId = localStorage.getItem("roleId");
    if (roleId == 1) {
      this.timeParames.compid = localStorage.getItem("compid");
    } else {
      this.timeParames.compid = localStorage.getItem("choseCompanyId");
    }
    this.timeParames.UserName = localStorage.getItem("userName");
    this.timeParames.startTime = timeCalculation(new Date(), "subtract", 7);
    this.timeParames.endTime = timeCalculation(new Date(), "subtract", 1);
    this.initCHART();
  },
  methods: {
    disabledDate(current) {
      return current && current > moment().startOf('day');
    },
    ondateChange(dates, datestring) {
      this.timeParames.startTime = datestring[0];
      this.timeParames.endTime = datestring[1];
      this.initCHART();
    },
    //所有默认显示的图表初始化
    initCHART() {
      this.Rankto();
      this.DayProduceSum(); //某时间段每天产量
      this.initline();
      this.GroupTimeActivation();
      this.GroupQualityActivation();
    },

    //运行时间排名
    GroupRunRank() {
      api.GroupRunRank(this.timeParames).then((res) => {
        let list = res.Data;
        let expectedData = [];
        let dates = [];
        list.forEach((item) => {
          expectedData.push((item.run/60).toFixed(2));
          dates.push(item.macname);
        });
        this.chartDataBarsort.expectedData = expectedData;
        this.chartDataBarsort.date = dates;
      });
    },
    //时间段内某天的产量
    DayProduceSum() {
      api.DayProduceSum(this.timeParames).then((res) => {
        let list = res.Data;
        
        // let expectedData = [];
        // let dates = [];
        // list.forEach((item) => {
        //   expectedData.push(item.num);
        //   dates.push(item.day);
        // });
        
        // console.log(expectedData)
        // this.chartDataBar.expectedData = expectedData;
        // this.chartDataBar.date = dates;
         this.havebardata(list)
      });
    },
    //半年内每月产量
    HalfYearProduceSum() {
      api.HalfYearProduceSum(this.timeParames).then((res) => {
        let list = res.Data;
        // let expectedData = [];
        let dates = [];
        // list.forEach((item) => {
        //   expectedData.push(item.num);
        //   dates.push(item.day);
        // });
        // this.chartDataBar.expectedData = expectedData;
        // this.chartDataBar.date = dates;
        this.havebardata(list, "month")
      });
    },
      //产量数据转换
    havebardata(list, time) {
      console.log(list);
      let expectedData = [];
      let name = [];
      let dates = null;
      if (time == "month") {
        //每月
        let startTime = this.timeParames.startTime.substring(0, 7);
        let endTime = this.timeParames.endTime.substring(0, 7);
        dates = getYearAndMonth(startTime, endTime);
      } else {
        //每天
        dates = getDayAll(this.timeParames.startTime, this.timeParames.endTime);
      }
    
        dates.forEach((items) => {
          let opt = null;
          if (time == "month") {
            opt = list.find(
              (day) => day.day == items
            ); //每月
          } else {
            opt = list.find((day) => day.day == items); //每天
          }
          if (opt) {
                expectedData.push(opt.num);
          } else {
            expectedData.push(0);
          }
      });
      this.chartDataBar.expectedData = expectedData;
        this.chartDataBar.date = dates;
      console.log(this.chartData);
    },
    //某时间段开机率
    GroupOnlineRate() {
      api.GroupOnlineRate(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list, 1, 1);
      });
    },
    //查询时间段内各产线的运行时间（分钟）
    GroupRunTime() {
      api.GroupRunTime(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list);
      });
    },
    //查询时间段内各产线的故障时间（分钟）
    GroupAlarmTime() {
      api.GroupAlarmTime(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list);
      });
    },
    //查询半年内各产线每月的开机率
    HalfYearGroupOnlineRate() {
      api.HalfYearGroupOnlineRate(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list, "month", 1);
      });
    },
    //查询厂半年内各产线的运行时间（分钟)
    HalfYearGroupRunTime() {
      api.HalfYearGroupRunTime(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list, "month");
      });
    },
    //查询厂半年内各产线的故障时间（分钟）
    HalfYearGroupAlarmTime() {
      api.HalfYearGroupAlarmTime(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list, "month");
      });
    },
    // /格式化年月不带0的
    monthcomplement(val) {
      let month = val.split("-");
      let monthnum = month[1] <= 9 ? "0" + month[1] : month[1];
      let num = month[0] + "-" + monthnum;
      return num;
    },

    //折线图数据转换
    havelinedata(list, time, type) {
      console.log(list);
      let expectedData = [];
      let name = [];
      let dates = null;
      if (time == "month") {
        //每月
        let startTime = this.timeParames.startTime.substring(0, 7);
        let endTime = this.timeParames.endTime.substring(0, 7);
        dates = getYearAndMonth(startTime, endTime);
      } else {
        //每天
        dates = getDayAll(this.timeParames.startTime, this.timeParames.endTime);
      }
      list.forEach((item) => {
        let data = [];
        dates.forEach((items) => {
          let opt = null;
          if (time == "month") {
            opt = item.arrayData.find(
              (day) => this.monthcomplement(day.day) == items
            ); //每月
          } else {
            opt = item.arrayData.find((day) => day.day == items); //每天
          }
          if (opt) {
            if (type == 1) {
              data.push((opt.yData * 100).toFixed(2));
            } else {
              data.push((opt.yData / 60).toFixed(2));
            }
          } else {
            data.push(0);
          }
        });
        expectedData.push(data);
        name.push(item.macsn);
      });
      this.chartData.expectedData = expectedData;
      this.chartData.date = dates;
      this.chartData.name = name;
      console.log(this.chartData);
    },
    //某时间产量排名
    GroupProduceRank() {
      api.GroupProduceRank(this.timeParames).then((res) => {
        let list = res.Data;
       
        let expectedData = [];
        let dates = [];
        list.forEach((item) => {
          expectedData.push(item.count);
          dates.push(item.macname);
        });
        this.chartDataBarsort.expectedData = expectedData;
        this.chartDataBarsort.date = dates;
      });
    },
    //查询用户厂各产线时间稼动率
    GroupTimeActivation() {
      let params = {
        compid: this.timeParames.compid,
        startTime: this.timeParames.startTime,
        endTime: this.timeParames.endTime,
      };
      api.GroupTimeActivation(params).then((res) => {
        this.TimeActivationData = res.Data;
      });
    },
    //查询用户厂各产线性能稼动率
    GroupQualityActivation() {
      let params = {
        compid: this.timeParames.compid,
        startTime: this.timeParames.startTime,
        endTime: this.timeParames.endTime,
      };
      api.GroupQualityActivation(params).then((res) => {
       this.QualityActivationData = res.Data;
      });
    },
    onTabChange(key, type) {
      this[type] = key;
      if (key == 1) {
        this.str = "%";
      } else {
        this.str = "小时";
      }
      if (this.dateType == 3) {
        this.initlineyear();
      } else {
        this.initline();
      }
    },
    //折线图
    initline() {
      if (this.noTitleKey == 1) {
        this.GroupOnlineRate(); //开机率
      } else if (this.noTitleKey == 2) {
        this.GroupRunTime(); //运行时间
      } else if (this.noTitleKey == 3) {
        this.GroupAlarmTime();
      }
    },
    //半年折线图
    initlineyear() {
      if (this.noTitleKey == 1) {
        this.HalfYearGroupOnlineRate(); //开机率
      } else if (this.noTitleKey == 2) {
        this.HalfYearGroupRunTime(); //运行时间
      } else if (this.noTitleKey == 3) {
        this.HalfYearGroupAlarmTime(); //故障时间
      }
    },

    onTabChangeSort(key, type) {
      this[type] = key;
      if (key == 1) {
        this.sortstr = "小时";
      } else {
        this.sortstr = "个";
      }
      this.Rankto();
    },
    Rankto() {
      if (this.noTitleKeysort == 1) {
        this.GroupRunRank(); //时间排名
      } else {
        this.GroupProduceRank(); //产量排名
      }
    },
    onTabChangepro(key, type) {
      this[type] = key;
    },
    changedate(val) {
      this.dateType = val;
      if (val == 1) {
        //一周
        this.timeParames.startTime = timeCalculation(new Date(), "subtract",7);
        this.timeParames.endTime = timeCalculation(new Date(), "subtract", 1);
        this.initCHART();
      } else if (val == 2) {
        //本月
        this.timeParames.startTime = formatCurrentMonth("start", 0);
        this.timeParames.endTime = formatCurrentMonth("end", 0);
        this.initCHART();
      } else if (val == 3) {
        //半年
        this.timeParames.startTime = formatCurrentMonth("start", -5);
        this.timeParames.endTime = timeCalculation(new Date(), "subtract", 1);
        this.Rankto();
        this.HalfYearProduceSum();
        this.HalfYearGroupOnlineRate();
        this.GroupTimeActivation();
      }
    },
  },
};
</script>

<style scoped lang="less">
@import "style.less";
</style>
